package com.lx.note.web;

import com.lx.common.constant.SessionConstant;
import com.lx.common.vo.Message;
import com.lx.note.entity.UserBO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * spring 容器中的权限控制 ,使用拦截器实现
 * User: Administrator
 * Date: 2018/06/02 下午 8:17
 */
@Component(value = "accessInterceptor")
public class AccessInterceptor implements HandlerInterceptor {

    private final static String register = "/user/register.do";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String path = request.getRequestURI();
        path = request.getContextPath();
        path = request.getServletPath();

        if(StringUtils.equals(register, path)){
            return true;
        }

        UserBO userBO = (UserBO)request.getAttribute(SessionConstant.KEY_LOGIN_USER);
        System.out.println(userBO);
        //如果用户已登录,则权限验证通过
        if(userBO == null){
            response.setContentType("text/html; charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.print(Message.fail("丫 没登录啊"));
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
